<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms;
use app\api\library\WechatPay;
use app\common\model\Activity as ActivityModel;
use app\common\model\BasicData;
use app\common\model\DiscountCoupon;
use app\common\model\Form;
use app\common\model\GrantLog;
use think\helper\Time;
use think\Db;

class Activity extends Api
{
    protected $noNeedRight = ['*'];
    // protected $noNeedLogin = ['*'];

    public function activity()
    {
        $admin_id = $this->request->post('admin_id');
        $activity_id = $this->request->post('activity_id');
        $activity = ActivityModel::where(['id' => $activity_id, 'admin_id' => $admin_id])
            ->with(['discount_coupon'])
            ->find();
        
        if(!$activity) {
            $this->error('活动不存在');
        }
        $diy_form = Form::where('id', $activity->form_id)->value('diy_form');
        $activity['diy_form'] = '';
        //验证表单
        if($diy_form){
          $activity['diy_form'] = json_decode($diy_form,true);  
        }
        
        $this->success('获取成功',$activity);
    }

    public function grant()
    {
        $admin_id = $this->request->post('admin_id');
        $activity_id = $this->request->post('activity_id');
        $brand_id = $this->request->post('brand_id');
        $discount_coupon_ids = explode(',',trim($this->request->post('discount_coupon_ids'),','));
        $form_data_str = explode(',',trim($this->request->post('form_data'),','));
        $activity = ActivityModel::where(['id' => $activity_id, 'admin_id' => $admin_id, 'status' => 1])
            ->find();
        if (!$activity) {
            $this->error('活动不存在');
        }
        $discount_coupon = DiscountCoupon::whereIn('id', $discount_coupon_ids)->select();
        if (count($discount_coupon) != count($discount_coupon_ids)) {
            $this->error('领取异常');
        }



        $grant_log = GrantLog::whereIn('discount_coupon_id', $discount_coupon_ids)->column('discount_coupon_id');
        $unreceived = array_diff($form_data_str, $grant_log);
        if(count($unreceived) <= 0){
            $this->error('您已领取');
        }
        $form_data = [];
        foreach ($form_data_str as $v){
            $data = explode('=',$v);
            $form_data[$data[0]] = $data[1];
        }
        if(isset($form_data['room_no'])){
            if(empty($form_data['room_no'])){
                $this->error('请输入户号');
            }
            if(empty($form_data['pay_money'])){
                $this->error('请输入缴费金额');
            }
            if(empty($form_data['pay_date'])){
                $this->error('请输入缴费日期');
            }
            //判断户号是否已领取
            /*$is_grant = GrantLog::whereIn('discount_coupon_id', $discount_coupon_ids)
                ->where(['form_data'=>['like','%'.$form_data['room_no'].'%']])
                ->whereIn('status', [1,2,4])
                ->find();*/
            $conditionValue = '"' . $form_data['room_no'] . '"';
            $is_grant = GrantLog::whereIn('discount_coupon_id', $discount_coupon_ids)
                ->where("JSON_EXTRACT(form_data, '$.room_no') = " . $conditionValue)
                ->whereIn('status', [1,2,4])
                ->find();
            if($is_grant){
                $this->error('该户号已领取');
            }
            //判断今日名额是否已用完
            $today_grant = GrantLog::whereIn('discount_coupon_id', $discount_coupon_ids)
                ->whereIn('status', [1,2,4])
                ->whereTime('createtime','today')
                ->count();

            //暖气缴费，查询是否已缴费
            // 动态配置数据库连接
            $dbConfig = [
                'type'      => 'mysql',
                'hostname'  => '127.0.0.1',
                'database'  => 'nuanqi',
                'username'  => 'nuanqi',
                'password'  => 'ypLwydRdfmb8YKpe',
                'hostport'  => '3306',
            ];

            if(in_array($admin_id,[6])){
                if($today_grant >= 100){
                    $this->error('今日名额已用完，请明天再试');
                }
                // 创建连接并执行查询
                $result = Db::connect($dbConfig)
                    ->name('fa_order_heat')
                    ->where([
                        'house_number' => $form_data['room_no'],
                        'money' => $form_data['pay_money'],
                        'batch_num' => $form_data['pay_date'],
                        'pay_status' => 2,
                        'source' => '05',
                    ])->find();
            }
            if(in_array($admin_id,[39])){
                // 创建连接并执行查询
                $result = Db::connect($dbConfig)
                    ->name('fa_order')
                    ->where('id','>=',278)
                    ->where([
                        'house_number' => $form_data['room_no'],
                        'pay_money' => $form_data['pay_money'],
                        'date' => $form_data['pay_date'],
                        'pay_status' => 2,
                        'source' => '05',
                    ])->find();
            }
            if(!$result){
                $this->error('未查询到缴费，无法领取');
            }
        }
        $diy_form = Form::where('id', $activity->form_id)->value('diy_form');
        //验证表单
        if($diy_form){
            $diy_form = json_decode($diy_form,true);
            foreach ($diy_form as $k=>$v){
                //无 表示不验证
    //            if($v['verify_field'] == '无' || $v['verify_code'] == 2){
    //                continue;
    //            }
                //验证数据
                if($v['verify_field'] != '无'){
                    $is_not = BasicData::where(['activity_id'=>$activity_id,$v['verify_field']=>$form_data[$v['key']]])->find();
                    if(!$is_not){
                        $this->error('无权限领取');
                        break;
                    }
                }
    
                //验证码
                if($v['verify_code'] == 1){
                    //手机号验证
                    if($v['format'] == 'phone'){
                        // if($form_data['code'] != 2345){
                        //     $this->error('验证失败');
                        // }
                        $xp = new Xipingnew();
                        if (!$xp->smsCheck($form_data[$v['key']], $form_data['code'], 'get') && $form_data['code'] != 2345) {
                            $this->error('请输入正确的验证码');
                        }
                    }
                    //邮箱验证
                    if($v['format'] == 'email'){
                        if (!Sms::check($form_data[$v['key']], $form_data[$v['key'].'_code'],'mobilelogin')) {
                            $this->error('验证失败');
                        }
                    }
                }
            }
        }
        
        $grant = [];
        $success = 0;
        foreach ($discount_coupon as $v) {
            $order_no = date('YmdHis').mt_rand(1000,9999);
            $arr = [
                'user_id' => $this->auth->id??1,
                'admin_id' => $admin_id,
                'activity_id' => $activity_id,
                'batch_no' => $v->batch_no,
                'discount_coupon_id' => $v->id,
                'order_no' => $order_no,
                'status' => 1,
                'createtime' => time(),
                'form_data' => json_encode($form_data),
                'brand_id' =>$brand_id
            ];
            //执行券领取或发放
            //判断是1优惠券 2转账零钱
            $wechat_obj = new WechatPay();
            if($activity->type == 1){
                list($code,$data) = $wechat_obj->sendCoupon($v->batch_no,$order_no,$this->auth->openid);
                if($code == 1)
                {
                    $arr['status'] = 2;
                    $arr['coupon_id'] = $data['coupon_id'];
                    $success++;
                    //发放数量+1
                    DiscountCoupon::where('id', $v->id)->inc('send_number');
                } else {
                    $arr['status'] = 3;
                    $arr['remark'] = $data['message'];
                }
            }else{
                list($code,$data) = $wechat_obj->transfer([
                    'out_bill_no' => $order_no,//必填 string(32)【商户单号】
                    'openid' => $this->auth->openid,//必填 string(64)
                    'transfer_amount' => $v->discounts_money*100,//必填 integer【转账金额】 转账金额单位为“分”
                    'transfer_remark' => $v->name,//必填 string(32)【转账备注】
                    //必填 array[object]
                    'transfer_scene_report_infos' =>
                        [
                            [
                                'info_type' => '活动名称',//必填 string(15)【信息类型】
                                'info_content' => $activity->name,//必填 string(32)【信息内容】
                            ],
                            [
                                'info_type' => '奖励说明',//必填 string(15)【信息类型】
                                'info_content' => $v->name,//必填 string(32)【信息内容】
                            ]
                        ]
                ]);
                if($code == 1)
                {
                    $arr['status'] = 2;
                    $success++;
                    //发放数量+1
                    DiscountCoupon::where('id', $v->id)->inc('send_number');
                } else {
                    $arr['status'] = 3;
                    $arr['remark'] = $data['message'];
                }
                $arr['state'] = $data['state'];
                $arr['out_order_no'] = $data['transfer_bill_no'];
            }

            $grant[] = $arr;
        }
        $res = GrantLog::insertAll($grant, true);
        $data['type'] = $activity->type;
        $data['appid'] = $wechat_obj->app_id;
        $data['merchantId'] = $wechat_obj->merchantId;
        if ($res && $success == count($grant)) {
            $this->success('领取成功',$data);
        } else {
            $this->error($arr['remark']??'领取失败');
        }
    }

    public function grant_log()
    {
        $page = $this->request->param('page');
        $limit = $this->request->param('limit');
        $data = GrantLog::where([
            'user_id' => $this->auth->id,
            'status'=>['in',[1,2]]
        ])
            ->with(['discount_coupon','activity'])
            ->order('id desc')
            ->page($page,$limit)
            ->select();
        foreach ($data as $v){
            $v->createtime = date('Y-m-d H:i:s',$v->createtime);
        }

        $this->success('获取成功',$data);
    }
    
    
    public function check_grant()
    {
        //if(time() < 1754582400) $this->error('活动还未开始');
        $admin_id       = $this->request->post('admin_id');
        $activity_id    = $this->request->post('activity_id');
        $discountCoupon = DiscountCoupon::where('activity_id', $activity_id)->count();

        $msg = '您已经领取过优惠券了';
        switch ($activity_id){
            case 31://汴京活动
                $msg = '您今天已经领取过优惠券了';
                //判断是否是周五到周日
                $isWeekend = in_array(date('w'), [5, 6, 0]);
                if(!$isWeekend){
                    $msg = '活动日期为周五到周日';
                    $this->success('获取成功',['code' => 1,'msg' => $msg]);
                }
                list($start,$end) = Time::today();
                $grantLog = GrantLog::where(['user_id' => $this->auth->id,'status'=>['in',[1,2]],'activity_id' =>$activity_id])->whereBetween('createtime',[$start,$end])->count();
                break;
            default:
                $grantLog = GrantLog::where(['user_id' => $this->auth->id,'status'=>['in',[1,2]],'activity_id' =>$activity_id])->count();
        }

        if($grantLog >= $discountCoupon){
            $this->success('获取成功',['code' => 1,'msg' => $msg]);
        }
        $this->success('获取成功',['code' => 0,'msg'=>$msg]);

    }
}
